package com.sweets.look.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.sweets.look.R;
import com.sweets.look.database.DatabaseHandler;
import com.sweets.look.ui.browser.BookmarkManager;
import com.sweets.look.util.BrowserUtils;

public class SearchAdapter extends BaseAdapter implements Filterable {
    class SearchFilter extends Filter {

        @Override
        protected Filter.FilterResults performFiltering(CharSequence constraint) {

            Filter.FilterResults v6 = new Filter.FilterResults();
            ArrayList<HistoryItem> v3 = new ArrayList<>();
            if (constraint == null || (constraint.toString().trim().isEmpty())) {
                if (mBookmarks != null) {
                    mBookmarks.clear();
                }

                if (mHistory == null) {
                    return v6;
                }

                mHistory.clear();
                ClipData v2 = ((ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE)).getPrimaryClip();
                if (v2 == null) {
                    return v6;
                }

                if (v2.getItemCount() <= 0) {
                    return v6;
                }

                if (v2.getItemAt(0).getText().toString().isEmpty()) {
                    return v6;
                }

                if (!BrowserUtils.isURL(v2.getItemAt(0).getText().toString())) {
                    if (BrowserUtils.isURL(v2.getItemAt(0).getText().toString())) {
                        return v6;
                    } else if (v2.getItemAt(0).getText().toString().length() <= 40) {
                    } else {
                        return v6;
                    }
                }

                mHistory.add(new HistoryItem(v2.getItemAt(0).getText().toString(),
                        mContext.getResources().getString(R.string.open_or_search), R.drawable.ic_history));
            } else {
                if (mBookmarks != null) {
                    mBookmarks.clear();
                } else {
                    mBookmarks = new ArrayList<>();
                }

                if (mHistory != null) {
                    mHistory.clear();
                } else {
                    mHistory = new ArrayList<>();
                }

                String v5 = constraint.toString().trim().toLowerCase(Locale.getDefault());
                int v1 = 0;
                mBookmarks = new ArrayList<>();
                int v4;
                for (v4 = 0; v4 < mAllBookmarks.size(); ++v4) {
                    if (v1 >= 5) {
                        break;
                    }

                    if (mAllBookmarks.get(v4).getTitle().toLowerCase(Locale.getDefault())
                            .startsWith(v5)) {
                        v3.add(mAllBookmarks.get(v4));
                        mBookmarks.add(mAllBookmarks.get(v4));
                        ++v1;
                    } else if (mAllBookmarks.get(v4).getUrl().contains(v5)) {
                        v3.add(mAllBookmarks.get(v4));
                        mBookmarks.add(mAllBookmarks.get(v4));
                        ++v1;
                    }
                }

                if (mDatabaseHandler == null || !mDatabaseHandler.isOpen()) {
                    mDatabaseHandler = new DatabaseHandler(mContext);
                }

                mHistory = mDatabaseHandler.findItemsContaining(v5);
                for (v4 = 0; v4 < mHistory.size(); ++v4) {
                    if (v4 >= 5) {
                        break;
                    }

                    v3.add(mHistory.get(v4));
                }

                v6.count = v3.size();
                v6.values = v3;
            }

            return v6;
        }

        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            synchronized (mFilteredList) {
                mFilteredList = getSuggestions();
                notifyDataSetChanged();
            }
        }
    }

    class SuggestionHolder {
        ImageView mImage;
        TextView mTitle;
        TextView mUrl;
    }

    private List<HistoryItem> mAllBookmarks;
    private final BookmarkManager mBookmarkManager;
    private List<HistoryItem> mBookmarks;
    private final Context mContext;
    private DatabaseHandler mDatabaseHandler;
    private List<HistoryItem> mFilteredList;
    private List<HistoryItem> mHistory;

    public SearchAdapter(Context context) {
        super();
        this.mDatabaseHandler = new DatabaseHandler(context);
        this.mFilteredList = new ArrayList<>();
        this.mHistory = new ArrayList<>();
        this.mBookmarks = new ArrayList<>();
        this.mBookmarkManager = new BookmarkManager(context);
        this.mAllBookmarks = this.mBookmarkManager.getBookmarks();
        this.mContext = context;
    }

    public int getCount() {
        int v0 = this.mFilteredList != null ? this.mFilteredList.size() : 0;
        return v0;
    }

    public Filter getFilter() {
        return new SearchFilter();
    }

    public Object getItem(int position) {
        return this.mFilteredList.get(position);
    }

    public long getItemId(int position) {
        return 0;
    }

    private List<HistoryItem> getSuggestions() {

        ArrayList<HistoryItem> v1 = new ArrayList<>();
        int historySize = 0;
        int bookSize = 0;
        if (this.mHistory != null && this.mHistory.size() > 0) {
            historySize = this.mHistory.size();
        }

        if (this.mBookmarks != null && this.mBookmarks.size() > 0) {
            bookSize = this.mBookmarks.size();
        }

        int v4 = 5;
        int v3 = 5;
        if (bookSize < 5) {
            v4 = 10 - bookSize;
        } else if (historySize < 5) {
            v3 = 10 - historySize;
        }


        for (int i = 0; i < bookSize; ++i) {
            if (i >= v3) {
                break;
            }
            try {
                v1.add(this.mBookmarks.get(i));
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < historySize; ++i) {
            if (i >= v4) {
                break;
            }

            try {
                v1.add(this.mHistory.get(i));
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }

        return v1;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        SuggestionHolder holder;
        if (convertView == null) {
            convertView = ((Activity) this.mContext).getLayoutInflater().inflate(R.layout.browser_input_hint, parent, false);
            holder = new SuggestionHolder();
            holder.mTitle = (TextView) convertView.findViewById(R.id.title);
            holder.mUrl = (TextView) convertView.findViewById(R.id.url);
            holder.mImage = (ImageView) convertView.findViewById(R.id.suggestionIcon);
            convertView.setTag(holder);
        } else {
            holder = (SuggestionHolder) convertView.getTag();
        }

        HistoryItem item = this.mFilteredList.get(position);
        holder.mTitle.setText(item.getTitle());
        holder.mUrl.setText(item.getUrl());
        int drawableId;
        switch (item.getImageId()) {
            case R.drawable.ic_bookmark: {
                drawableId = R.drawable.ic_bookmark;
                break;
            }
            case R.drawable.ic_history: {
                drawableId = R.drawable.ic_history;
                break;
            }
            case R.drawable.titlebar_search: {
                drawableId = R.drawable.titlebar_search;
                break;
            }
            default: {
                drawableId = R.drawable.ic_webpage;
                break;
            }
        }

        holder.mImage.setImageDrawable(this.mContext.getResources().getDrawable(drawableId));
        return convertView;
    }

    public void refreshBookmarks() {
        this.mAllBookmarks = this.mBookmarkManager.getBookmarks();
    }

    public void setContents(List<HistoryItem> list) {
        if (this.mFilteredList != null) {
            this.mFilteredList.clear();
            this.mFilteredList.addAll(list);
        }
    }
}

